package com.dreamer.repository.pyramid;

import com.dreamer.domain.pyramid.Pyramid;
import com.dreamer.domain.pyramid.PyramidUser;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;
import ps.mx.otter.utils.SearchParameter;
import ps.mx.otter.utils.dao.hibernate.HibernateBaseDAO;

import java.util.List;

@Repository("pyramidDAO")
public class PyramidDAO extends HibernateBaseDAO<Pyramid> {

    private Session getCurrentSession() {
        return getSessionFactory().getCurrentSession();
    }

    public List<Pyramid> searchAllByPage(SearchParameter<Pyramid> p) {
        return super.searchEntityByPage(p, (t) -> {
            Example example = Example.create(t.getEntity()).enableLike(MatchMode.ANYWHERE);
            Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(getClazz());
            criteria.add(example);
            return criteria;
        }, (o)-> true);
    }

    public void save(Pyramid transientInstance) {

        try {
            getCurrentSession().save(transientInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public void delete(Pyramid persistentInstance) {
        try {
            getCurrentSession().delete(persistentInstance);

        } catch (RuntimeException re) {

            throw re;
        }
    }

    public Pyramid findById(Integer id) {

        try {
            Pyramid instance = (Pyramid) getCurrentSession().get(
                    "com.dreamer.domain.pyramid.Pyramid", id);
            return instance;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public Pyramid findBySort(Integer id) {
        String queryString = "from Pyramid p where p.sort= :id";
        Query queryObject = getCurrentSession().createQuery(queryString);
        queryObject.setParameter("id",id);
        return (Pyramid) queryObject.list().get(0);
    }

    public Pyramid merge(Pyramid detachedInstance) {
        try {
            Pyramid result = (Pyramid) getCurrentSession().merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {

            throw re;
        }
    }

    public List<Pyramid> findAll() {
        try {
            String queryString = "from Pyramid";
            Query queryObject = getCurrentSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            throw re;
        }
    }

    //TODO 获取金字塔的关卡和层数信息，一定要排序
    public List<Pyramid> getPyramidAll() {
        String queryString = "from Pyramid p where 1=1 order by p.sort asc";
        Query queryObject = getCurrentSession().createQuery(queryString);
        return queryObject.list();
    }

}
